/********************************************************************************
 * Project Name		[OpenSourcePractices]
 * File Name     	[TestDbcp.java]
 * Creation Date 	[2015-01-01]
 * 
 * Copyright© ge.y.yang@gmail.com All Rights Reserved
 * 
 * Work hard, play harder, think big and keep fit
 ********************************************************************************/
package commons.dbcp;

import java.sql.Connection;
import java.util.Properties;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.junit.Test;

/**
 * DBCP连接池需要三个包<br/>
 * 
 * commons.dbcp2<br/>
 * commons.logging<br/>
 * commons.pool2<br/>
 * 
 * @author 不落的太阳(Sean Yang aka ShortPeace)
 * @version 1.0
 * @since jdk 1.8
 * 
 */
public class TestDbcp {

	/**
	 * 使用BasicDataSource创建DataSource和Connection
	 * 
	 * @throws Exception
	 */
	@Test
	public void testDbcp1() throws Exception {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUsername("root");
		dataSource.setPassword("123456");
		dataSource.setUrl("jdbc:mysql:///jdbc");
		// 设置初始化连接数
		dataSource.setInitialSize(10);
		// 设置最大连接数
		dataSource.setMaxTotal(30);
		// 设置最大空闲连接数
		dataSource.setMaxIdle(10);
		// 指定等待数据库连接池分配连接的最长时间, 超过该时间将抛出异常
		dataSource.setMaxWaitMillis(1000 * 5);
		// 设置默认提交
		dataSource.setDefaultAutoCommit(false);

		Connection connection = dataSource.getConnection();
		System.out.println(connection);
		connection.close();
		dataSource.close();
	}

	/**
	 * 使用BasicDataSourceFactory和配置文件创建DataSource和Connection
	 * 
	 * @throws Exception
	 */
	@Test
	public void testDbcp2() throws Exception {
		Properties properties = new Properties();
		properties.load(this.getClass().getClassLoader().getResourceAsStream("commons/dbcp/dbcpconfig.properties"));

		BasicDataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
		Connection connection = dataSource.getConnection();
		System.out.println(connection);
		connection.close();
		dataSource.close();
	}
}
